/**
 * 请不要直接引用,如需引用,请使用
 * import http from '@/common/api/tslm-api.js'
 */
import Request from '@/js_sdk/luch-request/luch-request/index.js'
import appConfig from '@/common/app-config.js';
import appUser from '@/common/app-user.js';
import logUtils from '@/common/log-utils.js';
import md5 from '@/js_sdk/ccdzhang-dokey/md5.js';

const refreshTokenUrl = '/auth/refreshTokenForBusiness';

const showLog = (tag, msg) => {
	logUtils(tag, msg);
}

const getAuthorization = (url) => {
	return url.indexOf(refreshTokenUrl) != -1 ? appUser.tokenInfo.refresh_token : appUser.tokenInfo
		.access_token;
}

const getToken = (data, secret = '') => {
	let str = secret;
	for (let key in data) {
		if (data[key] == '') {
			continue;
		}
		str += key;
		str += data[key];
	}
	let regExp = new RegExp(' ', 'g');
	str = str.replace(regExp, '').toLowerCase();
	let chars = str.split('');
	let charStr = chars.sort().join('');
	let token = md5(JSON.stringify(charStr));
	return token;
}

const getAppRequest = (config) => {
	return {
		url: config.fullPath ? config.fullPath : `${config.baseURL}${config.url}`,
		header: config.header,
		data: config.data
	};
}

const getAppResponse = (responseData) => {
	return responseData ? {
		code: responseData.errorCode,
		msg: responseData.errorMsg,
		data: responseData.data
	} : {
		code: 102,
		msg: "当前网络异常",
	};
}

const http = new Request()
// 设置全局配置
http.setConfig((config) => {
	appConfig.init();
	appUser.init();
	// 根域名
	config.baseURL = appConfig.apiDomain;
	config.header = {
		...config.header,
		baseVersion: appConfig.baseVersion,
		version: appConfig.version,
		systemType: appConfig.systemType,
	}
	return config
})

// 请求之前拦截器。可以使用async await 做异步操作
http.interceptors.request.use((config) => {
	config.header = {
		...config.header,
		timeStamp: new Date().getTime(),
		Authorization: getAuthorization(config.url),
		sign: getToken(config.data),
		deviceId: appConfig.deviceId,
	}
	// if (!token) { 
	// 如果token不存在，return Promise.reject(config) 会取消本次请求
	// 	return Promise.reject(config)
	// }
	// showLog('http requestLog ', config);
	return config
}, (config) => {
	showLog('http requestLog error', config);
	return Promise.reject(config)
})

// 请求之后拦截器。可以使用async await 做异步操作
// 成功的消息代码 0
http.interceptors.response.use(async (response) => {
	return responseManage(response);
}, (response) => {
	// 请求错误做点什么。可以使用async await 做异步操作
	return responseManage(response);
})

const responseManage = (response) => {
	// showLog('http responseManage ', response);
	let res = response.data;
	//请求返回体
	let appResponse = getAppResponse(res);
	//请求发送体
	let appRequest = getAppRequest(response.config);
	appResponse.request = appRequest;
	showLog('http responseLog ', appResponse);
	//状态码
	switch (Number(appResponse.code)) {
		case 0:
			return appResponse.data
		default:
			// 服务端返回的状态码不等于101，则reject()
			uni.showToast({
				title: appResponse.msg,
				duration: 2000,
				icon: 'none'
			})
			return Promise.reject(appResponse)
	}
}

export default http
